<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/17 0017
 * Time: 上午 10:44
 */
namespace app\member\controller;
use app\common\api\member\IMember;
use app\member\validate\Vali_mem;
use app\member\validate\ValidateFun;
use think\Db;
use think\Controller;

class Member implements IMember {
    private static $config = [];
    /**
     * 初始化配置
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        self::$config = array_filter_full(array_merge(self::$config,$config));
    }

    /**
     * 登录
     * @return mixed
     */
    public function login(){
        $data = self::$config;

        #验证参数
        $vali = Vali_mem::login();
        $validate = new ValidateFun($vali['rule'],$vali['message']);
        if (!$validate->check($data)){
            $err = $validate->getError();
            return ['code'=>$err,'msg'=>config("msg.$err")];
        }
        #找出登录这信息
        $info = new \app\member\model\Member();
        $res = $info->login($data);


        #插入登录日志
        $d = [
            'uid'   => $res['id'],
            'lasttime'=>date('Y-m-d H:i:s'),
            'lastip'    =>get_ip(),
            'status'    =>1,
            'del'       =>1
        ];
        $log = $info->login_log($d);

        #返回结果
        if ($log>0){
            unset($res['code'],$res['password'],$res['del']);
            $res['lasttime'] = $d['lasttime'];
            return ['code'=>200,'msg'=>config('msg.200'),'data'=>$res];
        }
        else{
            return ['code'=>400,'msg'=>config('msg.400')];
        }
    }

    /**
     * 注册
     * @return mixed
     */
    public function register(){
        $default_data = [
            'phone'     =>'',
            'del'       =>1,
            'createtime'=>date('Y-m-d H:i:s'),
            'updatetime'=>date('Y-m-d H:i:s'),
            'password'  =>'123456',
            'identity'  =>100,
            'img'       =>'public/static/images/timg.jpg'
        ];
        $data = array_filter_full(array_merge($default_data,self::$config));


        #验证参数
        $vali = Vali_mem::register();
        $validate = new ValidateFun($vali['rule'],$vali['message']);
        if (!$validate->check($data)){
            $err = $validate->getError();
            return ['code'=>$err,'msg'=>config("msg.{$err}")];
        }
        unset($data['id'],$data['password_confirm']);
        #数据库数据处理
        $data['code'] =getCode(6);
        $data['password']=getMd5($data['password'],$data['username'],$data['code']);

        #添加用户
        $add =  new \app\member\model\Member();
        $res = $add ->mem_add($data);
        #返回结果
        if ($res>0){
            return ['code'=>200,'msg'=>config('msg.200')];
        }else{
            return ['code'=>10006,'msg'=>config('msg.10006')];
        }
    }

    /**
     * 获取用户详情
     * @return mixed
     */
    public function info(){
        $data = self::$config;

        #验证参数
        $vali = Vali_mem::info();
        $validate = new ValidateFun($vali['rule'],$vali['message']);
        if (!$validate->check($data)){
            $err = $validate->getError();
            return ['code'=>$err,'msg'=>config("msg.$err")];
        }
        #获取信息
        $info = new \app\member\model\Member();
        $res = $info->mem_info($data);
        unset($res['password'],$res['code'],$res['del']);
        #返回结果
        return ['code'=>200,'msg'=>config('msg.200'),'data'=>$res];
    }

    /**
     * 更改用户信息
     * @return mixed
     */
    public function update(){
        $session = session('admin_info');
        $default_data = [
            'id'        => $session['id'],
            'updatetime'=>date('Y-m-d H:i:s')
        ];
        $data = array_filter_full(array_merge($default_data,self::$config));

        #验证参数
        $vali = Vali_mem::update();
        $validate = new ValidateFun($vali['rule'],$vali['message']);
        if (!$validate->check($data)){
            $err = $validate->getError();
            return ['code'=>$err,'msg'=>config("msg.$err")];
        }
        if (isset($data['oldpwd'])||isset($data['newpwd'])){
            $vali = Vali_mem::_info();
            $validate = new ValidateFun($vali['rule'],$vali['message']);
            if (!$validate->check($data)){
                $err = $validate->getError();
                return ['code'=>$err,'msg'=>config("msg.$err")];
            }
        }

        #整理数据库所需的数据
        if (isset($data['newpwd'])){
            $info = new \app\member\model\Member();
            $infos = $info->mem_info($data);
            $data['password'] = getMd5($data['newpwd'],$infos['username'],$infos['code']);
            unset($data['newpwd'],$data['oldpwd'],$data['newpwd_confirm']);
        }

        #修改数据
        $update = new \app\member\model\Member();
        $res = $update->mem_update($data);

        #返回结果
        return $res;
    }

    /**
     * 用户列表
     * @return mixed
     */
    public function user_list(){
        $default =[
            'curr' =>1,
            'limits'=>10,
        ];
        $data = array_filter_full(array_merge($default,self::$config));
        #获取列表
        $list = new \app\member\model\Member();
        $result =$list->mem_list($data);
        #返回结果
        return ['code'=>200,'msg'=>config('msg.200'),'data'=>$result];
    }

    /**
     * 删除用户
     */
    public function del(){
        $data = self::$config;
        $vali = Vali_mem::info();
        $validate = new ValidateFun($vali['rule'],$vali['message']);
        if (!$validate->check($data)){
            return ['code'=>$validate->getError(),'msg'=>config("msg.".$validate->getError())];
        }
        $del = new \app\member\model\Member();
        $res = $del->del($data);

        if ($res>0){
            return ['code'=>200,'msg'=>config('msg.200')];
        }else{
            return ['code'=>10007,'msg'=>config('msg.10007')];
        }
    }

    /**
     * 导入用户
     * @return mixed
     */
    public function user_import(){
        #获取参数
        $data = self::$config;

        #验证参数
        if(empty($data['file_path'])){
            return ['code'=>10003,'msg'=>config('msg.10003')];#缺少参数
        }

        #获取excel表数据
        $obj = new \app\common\controller\Export(['file_path'=>$data['file_path']]);
        $res = $obj->import();

        #得到数组
        $list_arr = isset($res['list'][1])?$res['list'][1]:[];
        $data=['list'=>$list_arr];

        /**
         * 批量导入
         */
        $list = isset($data['list'])?$data['list']:[];
        if(!is_array($list) || count($list) == 0 || empty($list)){
            return ['code'=>10033,'msg'=>config('msg.10033')];#导入数据为空
        }

        #判断模板是否正确
        $hea = $list[1];
        if($hea['A'] != '教材名称'
            || $hea['B'] != '学段'
            || $hea['C'] != '学科'
            || $hea['D'] != '年级'
            || $hea['E'] != '出版社'
            || $hea['F'] != '封面图'
        ){
            return ['code'=>10034,'msg'=>config('msg.10034')];#导入模板错误
        }

        #启动事务
        $err_msg = '';
        $status = 1;
        Db::startTrans();

        $excel_list = array_splice($list,2);#excel的数据，从第3行开始读起
        if(count($excel_list) == 0 || empty($excel_list)){
            return ['code'=>10035,'msg'=>config('msg.10035')];#导入数据错误
        }

        #重新组合数组
        $new_list = [];
        foreach ($excel_list as $k=>$v){
            $new_list[$k]['name'] = $v['A'];
            $new_list[$k]['xueduanid'] = Db::name('pad_xueduan')->where(['name'=>$v['B'],'del'=>1])->value('id');
            $new_list[$k]['xuekeid'] = Db::name('pad_xueke')->where(['name'=>$v['C'],'del'=>1])->value('id');
            $new_list[$k]['nianjiid'] = Db::name('pad_nianji')->where(['name'=>$v['D'],'del'=>1])->value('id');
            $new_list[$k]['pressid'] = Db::name('pad_press')->where(['name'=>$v['E'],'del'=>1])->value('id');
            $new_list[$k]['icon'] = $v['F'];
        }

        #插入数据
        foreach ($new_list as $k=>$v){
            $Knum = $k+3;

            $name = isset($v['name'])?$v['name']:'';
            $xueduanid = isset($v['xueduanid'])?$v['xueduanid']:'';
            $xuekeid = isset($v['xuekeid'])?$v['xuekeid']:'';
            $nianjiid = isset($v['nianjiid'])?$v['nianjiid']:'';
            $pressid = isset($v['pressid'])?$v['pressid']:'';

            #验证name，xueduanid，xuekeid,nianjiid,pressid字段是否正确
            $check_data =[
                'name'      =>$name,
                'xueduanid' =>$xueduanid,
                'xuekeid'   =>$xuekeid,
                'nianjiid'  =>$nianjiid,
                'pressid'   =>$pressid
            ];
            $vali = \app\resources\validate\Material::teach_import();
            $validate = new ValidateFun($vali['rule'], $vali['message']);
            if(!$validate->check($check_data)){
                $status = 0;
                $err_msg = "发生错误，第".$Knum."条数据，".config('msg.'.$validate->getError());
                break;
            }

            #添加数据
            $check_data['createtime'] = time();
            $teach_res = new \app\member\model\Member();
            $res = $teach_res->user_import($check_data);

            if($res > 0){
                $Knum = $Knum-2;
                $err_msg = '导入成功，导入数据:'.$Knum.'条';
            }else{
                $status = 0;
                $err_msg = "发生错误，第".$Knum."条数据，".config('msg.10035');#导入数据错误
                break;
            }
        }

        if($status == 0){
            #回滚事务
            Db::rollback();
            return ['code'=>400,'msg'=>$err_msg];
        }else{
            #提交事务
            Db::commit();
            return ['code'=>200,'msg'=>$err_msg];
        }
    }

    /**
     * 导出用户信息
     * @return mixed
     */
    public function user_export(){
        $data = self::$config;

        /**
         * 获取表内容
         */
        $export = new \app\member\model\Member();
        $result = $export->user_export($data);
        $list = [];
        if($result['code'] == 200){
            $list = $result['data'];
        }

        $list_res = [];
        foreach ($list as $k=>$v){
            $list_res[$k]['id'] = $v['id'];
            $list_res[$k]['username'] = $v['username'];
            $list_res[$k]['email'] = $v['email'];
            $list_res[$k]['phone'] = $v['phone'];
            $list_res[$k]['introduce'] = $v['introduce'];
            $list_res[$k]['img'] = $v['img'];
            $list_res[$k]['role_name'] = $v['role_name'];
        }
        #设置导出表头
        $table_hea = ['ID','用户账号','邮箱','手机号','介绍','头像','角色'];

        #导出excel表数据
        $obj = new \app\common\controller\Export(['table_data'=>$list_res,'table_header'=>$table_hea]);
        $obj->export();
    }

/*    public function admin_update(){
    $data = self::$config;
    #验证参数
    $vali = Vali_mem::info();
    $validate = new ValidateFun($vali['rule'],$vali['message']);
    if (!$validate->check($data)){
        $err = $validate->getError();
        return ['code'=>$err,'msg'=>config("msg.$err")];
    }
    #修改数据
    $update = new \app\member\model\Member();
    $res = $update->mem_update($data);
    #返回结果
    if ($res>0){
        return ['code'=>200,'msg'=>config('msg.200')];
    }else{
        return ['code'=>10007,'msg'=>config('msg.10007')];#数据修改失败
    }
}*/

}